﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Hangjing.Model;
using System.Web;
using System.Collections;

using Hangjing.Common;
using Hangjing.SQLServerDAL;
using Hangjing.AppLog;

namespace Hangjing.meituanapi
{
    /// <summary>
    /// 美团外卖相关api
    /// </summary>
    public class mthelper
    {
        public HttpContext context = null;

        /// <summary>
        /// 参数列表
        /// </summary>
        private Hashtable parameters;


        /// <summary>
        /// 访问链接
        /// </summary>
        public string serverurl
        {
            set;
            get;
        }

        /// <summary>
        /// 
        /// </summary>
        public mthelper(HttpContext _context)
        {
            parameters = new Hashtable();
            parameters.Add("charset", "UTF-8");
            parameters.Add("version", "1");
            parameters.Add("timestamp", Utils.getTimestamp());

            context = _context;

        }

        public apiResultInfo shopOnline(int shopid)
        {
            apiResultInfo rs = new apiResultInfo();

            meituanbindlogInfo record = new meituanbindlog().GetList(1, 1, "ePoiId=" + shopid + " and mtype=1", "mid", 1).FirstOrDefault();
            if (record == null)
            {
                OperationLog.Warn("商家：" + shopid + "未找到绑定token");
                rs.msg = "商家：" + shopid + "未找到绑定token";
                return rs;
            }

            parameters.Add("appAuthToken", record.appAuthToken);

            createSHA1Sign();


            HttpItem objHttpItem = new HttpItem()
            {
                Encoding = "utf-8",
                Method = "POST"
            };


            string url = "http://api.open.cater.meituan.com/waimai/poi/open";
            string returnmsg = queryData(objHttpItem, url);

            mtresult result = Newtonsoft.Json.JsonConvert.DeserializeObject<mtresult>(returnmsg);

            if (result.data != null && result.data.ToLower() == "ok")
            {
                rs.state = 1;

            }
            else
            {
                rs.msg = "商家上线失败";
            }


            return rs;
        }

        public apiResultInfo confirmOrder(string orderId, int shopid)
        {
            apiResultInfo rs = new apiResultInfo();

            meituanbindlogInfo record = new meituanbindlog().GetList(1, 1, "ePoiId=" + shopid + " and mtype=1", "mid", 1).FirstOrDefault();
            if (record == null)
            {
                OperationLog.Warn("商家：" + shopid + "未找到绑定token");
                rs.msg = "商家：" + shopid + "未找到绑定token";
                return rs;
            }

            parameters.Add("appAuthToken", record.appAuthToken);
            parameters.Add("orderId", orderId.Replace("m", ""));

            createSHA1Sign();


            HttpItem objHttpItem = new HttpItem()
            {
                Encoding = "utf-8",
                Method = "POST"
            };


            string url = "http://api.open.cater.meituan.com/waimai/order/confirm";
            string returnmsg = queryData(objHttpItem, url);

            mtresult result = Newtonsoft.Json.JsonConvert.DeserializeObject<mtresult>(returnmsg);

            if (result.data != null && result.data.ToLower() == "ok")
            {
                rs.state = 1;

            }
            else
            {


                rs.msg = "确认订单失败";
            }



            return rs;
        }



        /// <summary>
        /// sha1签名
        /// </summary>
        /// <returns></returns>
        public string createSHA1Sign()
        {
            StringBuilder sb = new StringBuilder();
            ArrayList akeys = new ArrayList(parameters.Keys);
            akeys.Sort();

            foreach (string k in akeys)
            {
                string v = HttpUtility.UrlEncode((string)parameters[k], Encoding.UTF8);
                if (null != v && "".CompareTo(v) != 0
                       && "sign".CompareTo(k) != 0)
                {

                    sb.Append(k+ v);

                }
            }


            string signstep2 = Constant.mt_SignKey + sb.ToString();

            string sig = Utils.SHA1_Hash(signstep2).ToLower();


            AppLog.AppLog.Info("美团签名=" + "signstep1=" + sb.ToString() + "\r\nsignstep2=" + signstep2 + "\r\n => sign:" + sig);


            return sig;
        }


        public string queryData(HttpItem objHttpItem, string url)
        {
            string sig = createSHA1Sign();
            parameters.Add("sign", sig);

            serverurl = url;
            ArrayList akeys = new ArrayList(parameters.Keys);

            StringBuilder sb = new StringBuilder();
            foreach (string k in akeys)
            {
                string v = context.Server.UrlEncode((string)parameters[k]);
                v = HttpUtility.UrlEncode(v, Encoding.UTF8);
                if (null != v && "".CompareTo(v) != 0)
                {
                    if (sb.Length == 0)
                    {
                        sb.Append(k + "=" + v);
                    }
                    else
                    {
                        sb.Append("&" + k + "=" + v);
                    }
                }
            }


            if (objHttpItem.Method.ToLower() == "get")
            {
                serverurl += "?" + sb.ToString();
            }
            else
            {
                objHttpItem.Postdata = sb.ToString();
            }


            HttpHelper objhttp = new HttpHelper();
            objHttpItem.URL = serverurl;


            objhttp.isToLower = false;
            string returnmsg = objhttp.GetHtml(objHttpItem);

            Hangjing.Common.HJlog.toLog("returnmsg=" + returnmsg + "\r\n url=" + serverurl);
            //  HJlog.toLog(this.getDebugInfo());

            return returnmsg;
        }


    }
}
